'use client'

import React, { useEffect, useRef } from 'react'
import { createPortal } from 'react-dom'
import {
    CheckCircleOutlined,
    ExclamationCircleOutlined,
    InfoCircleOutlined,
    CloseCircleOutlined,
    CloseOutlined,
    LoadingOutlined
} from '@ant-design/icons'
import { useUIStore } from '@/stores/uiStore'

// 通知项组件
interface NotificationItemProps {
    id: string
    type: 'success' | 'error' | 'warning' | 'info' | 'loading'
    title: string
    message?: string
    duration?: number
    actions?: Array<{
        label: string
        onClick: () => void
        type?: 'primary' | 'default'
    }>
    onClose: (id: string) => void
}

const NotificationItem: React.FC<NotificationItemProps> = ({
    id,
    type,
    title,
    message,
    actions,
    onClose
}) => {
    const timeoutRef = useRef<NodeJS.Timeout | null>(null)

    const getIcon = () => {
        switch (type) {
            case 'success':
                return <CheckCircleOutlined className="text-green-500" />
            case 'error':
                return <CloseCircleOutlined className="text-red-500" />
            case 'warning':
                return <ExclamationCircleOutlined className="text-yellow-500" />
            case 'info':
                return <InfoCircleOutlined className="text-blue-500" />
            case 'loading':
                return <LoadingOutlined className="text-blue-500" />
            default:
                return <InfoCircleOutlined className="text-gray-500" />
        }
    }

    const getBackgroundColor = () => {
        switch (type) {
            case 'success':
                return 'bg-green-50 border-green-200'
            case 'error':
                return 'bg-red-50 border-red-200'
            case 'warning':
                return 'bg-yellow-50 border-yellow-200'
            case 'info':
                return 'bg-blue-50 border-blue-200'
            case 'loading':
                return 'bg-blue-50 border-blue-200'
            default:
                return 'bg-gray-50 border-gray-200'
        }
    }

    const getTitleColor = () => {
        switch (type) {
            case 'success':
                return 'text-green-800'
            case 'error':
                return 'text-red-800'
            case 'warning':
                return 'text-yellow-800'
            case 'info':
                return 'text-blue-800'
            case 'loading':
                return 'text-blue-800'
            default:
                return 'text-gray-800'
        }
    }

    const getMessageColor = () => {
        switch (type) {
            case 'success':
                return 'text-green-700'
            case 'error':
                return 'text-red-700'
            case 'warning':
                return 'text-yellow-700'
            case 'info':
                return 'text-blue-700'
            case 'loading':
                return 'text-blue-700'
            default:
                return 'text-gray-700'
        }
    }

    const handleClose = () => {
        onClose(id)
    }

    return (
        <div className={`
            notification-item
            p-4 rounded-lg shadow-lg border max-w-sm w-full
            transform transition-all duration-300 ease-in-out
            animate-slide-in-right
            ${getBackgroundColor()}
        `}>
            <div className="flex items-start space-x-3">
                <div className="flex-shrink-0 mt-0.5">
                    {getIcon()}
                </div>

                <div className="flex-1 min-w-0">
                    <div className="flex items-start justify-between">
                        <h4 className={`font-medium text-sm ${getTitleColor()}`}>
                            {title}
                        </h4>
                        {type !== 'loading' && (
                            <button
                                onClick={handleClose}
                                className={`ml-2 flex-shrink-0 ${getTitleColor()} hover:opacity-70 transition-opacity`}
                            >
                                <CloseOutlined className="text-xs" />
                            </button>
                        )}
                    </div>

                    {message && (
                        <p className={`text-sm mt-1 ${getMessageColor()}`}>
                            {message}
                        </p>
                    )}

                    {actions && actions.length > 0 && (
                        <div className="flex space-x-2 mt-3">
                            {actions.map((action, index) => (
                                <button
                                    key={index}
                                    onClick={action.onClick}
                                    className={`
                                        px-3 py-1 text-xs rounded transition-colors
                                        ${action.type === 'primary'
                                            ? 'bg-blue-600 text-white hover:bg-blue-700'
                                            : 'bg-white border border-gray-300 text-gray-700 hover:bg-gray-50'
                                        }
                                    `}
                                >
                                    {action.label}
                                </button>
                            ))}
                        </div>
                    )}
                </div>
            </div>
        </div>
    )
}

// 通知容器组件
export const NotificationContainer: React.FC = () => {
    const { notifications, removeNotification } = useUIStore()
    const [mounted, setMounted] = React.useState(false)

    useEffect(() => {
        setMounted(true)
    }, [])

    if (!mounted || typeof window === 'undefined') {
        return null
    }

    const container = document.getElementById('notification-portal') || document.body

    return createPortal(
        <div className="notification-container fixed top-4 right-4 z-50 space-y-2 pointer-events-none">
            <div className="space-y-2 pointer-events-auto">
                {notifications.map(notification => (
                    <NotificationItem
                        key={notification.id}
                        id={notification.id}
                        type={notification.type as any}
                        title={notification.title}
                        message={notification.message}
                        onClose={removeNotification}
                    />
                ))}
            </div>
        </div>,
        container
    )
}

// 通知管理器Hook
export const useNotifications = () => {
    const { addNotification, removeNotification, clearNotifications } = useUIStore()

    const showSuccess = (title: string, message?: string, duration?: number) => {
        addNotification({
            type: 'success',
            title,
            message: message || '',
            duration: duration || 4000
        })
    }

    const showError = (title: string, message?: string, duration?: number) => {
        addNotification({
            type: 'error',
            title,
            message: message || '',
            duration: duration || 6000
        })
    }

    const showWarning = (title: string, message?: string, duration?: number) => {
        addNotification({
            type: 'warning',
            title,
            message: message || '',
            duration: duration || 5000
        })
    }

    const showInfo = (title: string, message?: string, duration?: number) => {
        addNotification({
            type: 'info',
            title,
            message: message || '',
            duration: duration || 4000
        })
    }

    const showLoading = (title: string, message?: string) => {
        const id = `loading_${Date.now()}_${Math.random().toString(36).substring(2, 9)}`
        addNotification({
            type: 'info', // 使用info类型，但在组件中特殊处理
            title,
            message: message || '',
            duration: 0 // 不自动消失
        })
        return id
    }

    const hideLoading = (id: string) => {
        removeNotification(id)
    }

    return {
        showSuccess,
        showError,
        showWarning,
        showInfo,
        showLoading,
        hideLoading,
        removeNotification,
        clearNotifications
    }
}

export default NotificationContainer